<template>
  <div class="container">
    <div class="mb10">
      <el-text class="mx-1"> 查询条件：</el-text>
    </div>
    <el-row :gutter="10">
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model="searchCondition.order_sn" clearable placeholder="请输入订单编号"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.mobile" placeholder="下单人手机号" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-date-picker v-model="queryDate" type="datetimerange" range-separator="至" format="YYYY-MM-DD HH:mm:ss" value-format="X" start-placeholder="创建时间" @change="changeQueryDate" end-placeholder="结束时间"> </el-date-picker>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-space wrap>
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-space>
      </el-col>
    </el-row>
    <div class="mb10">
      <el-text class="mx-1"> 查询结果：</el-text>
    </div>
    <el-table :data="tableList" border class="table" row-key="id" ref="multipleTableRef" v-loading="loading" :reserve-selection="true" @row-dblclick="rowDblclick">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="order_sn" label="订单编号" align="center"> </el-table-column>
      <el-table-column prop="user" label="下单人信息" align="center">
        <template #default="scope">
          <div class="ibDraggable">
            <div>姓名：{{ scope.row.name }}</div>
            <div>真实电话：{{ scope.row.mobile }}</div>
            <div>办卡号码：{{ scope.row.card_mobile }}</div>
            <div v-if="scope.row.store">绑定店铺：{{ scope.row.store.store_name }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="mobile_situation_label" label="优惠模式" align="center"> </el-table-column>
      <el-table-column prop="card_contract_package_name" label="套餐" align="center"> </el-table-column>
      <!-- <el-table-column prop="service_life_label"
                             label="号卡使用年限"
                             align="center">
            </el-table-column> -->
      <el-table-column prop="address" label="收货地址" align="center"> </el-table-column>
      <el-table-column prop="total_price" label="订单金额/元" align="center"> </el-table-column>
      <el-table-column prop="status_name" label="订单状态" align="center"> </el-table-column>
      <el-table-column prop="create_time" label="创建时间" align="center" :formatter="(row: INumberCardOrderInfoList) => handleVerifyFormatDate(row.create_time)"> </el-table-column>
      <el-table-column label="操作" width="210" align="center">
        <template #default="scope">
          <div class="control-flex">
            <el-button type="primary" link :icon="View" @click="handleViewEdit(scope.row, 'view')">查看</el-button>
            <div v-show="['to_be_paid', 'waiting_for_credit_authorization'].includes(scope.row.status)" v-permission="'cancelOrder'">
              <el-popconfirm placement="top" width="160" title="你确定要取消订单吗?" @confirm="handleCancelOrder(scope.row.id)">
                <template #reference>
                  <el-button link :icon="Close" type="danger">取消订单</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="searchCondition.size"
        :current-page="searchCondition.current"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        :hide-on-single-page="false">
      </el-pagination>
    </div>
  </div>
</template>

<script setup lang="ts">
import { View, Close, Search, Refresh } from "@element-plus/icons-vue";
import { handleVerifyFormatDate } from "@/utils/utils";
import type { ViewMode, ViewModeFilter } from "@/types/common";
import type { IDictData } from "@/types/dict";
import { useState } from "@/hooks/useState.ts";
import type { INumberCardOrderInfoList, ISearchNumberCardOrderInfo } from "@/types/rentMachineManage/numberCardOrderInfo";
import { getCardContractPackageOrderInfo, putCancelCardContractPackageOrderInfo } from "@/utils/api/cardContractPackageOrder";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  orderStatus: Array<IDictData>;
}
const { orderStatus } = defineProps<Props>();

const emit = defineEmits<{
  handleAdd: [code: ViewMode];
  handleToPrint: [ids: number[]];
  handleViewEdit: [id: number, code: ViewModeFilter];
}>();
/* 暴露一个方法给父组件使用 */
defineExpose({
  /* 这一步关键，在setup语法糖中使用时 */
  getTableInfo
});
const multipleTableRef = useTemplateRef("multipleTableRef"); /* 列表组件的引用 */
const queryDate = ref<Array<string>>([]);
const payTime = ref<Array<string>>([]);
const deliveryTime = ref<Array<string>>([]);
const total = ref(0);

const searchCondition = reactive<ISearchNumberCardOrderInfo>({
  order_sn: "",
  mobile: "",
  status: "",
  start_time: "",
  end_time: "",
  size: 10,
  current: 1
});
const tableList = ref<Array<INumberCardOrderInfoList>>([]);

/* 时间更改事件 */
function changeQueryDate(data: number[]) {
  if (data !== null) {
    searchCondition.start_time = data[0] * 1000;
    searchCondition.end_time = data[1] * 10000;
  } else {
    searchCondition.start_time = "";
    searchCondition.end_time = "";
  }
}
/* 搜索 */
function searchInfo() {
  searchCondition.current = 1;
  searchCondition.size = 10;
  getTableInfo();
}

/**
 * 重置搜索内容
 */
function resetSearch() {
  searchCondition.order_sn = "";
  searchCondition.mobile = "";
  searchCondition.status = "";
  searchCondition.start_time = "";
  searchCondition.end_time = "";

  queryDate.value = [];
  payTime.value = [];
  deliveryTime.value = [];
  searchCondition.current = 1;
  searchCondition.size = 10;

  getTableInfo();
}
/* 请求：获取表格中数据 */
function getTableInfo() {
  toggleState(true);
  getCardContractPackageOrderInfo<INumberCardOrderInfoList, ISearchNumberCardOrderInfo>(searchCondition)
    .then(res => {
      tableList.value = res.result.data;
      total.value = res.result.total;
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 显示第几页 */
function handleCurrentChange(val: number) {
  searchCondition.current = val;
  getTableInfo();
}

/* 每页显示几条 */
function handleSizeChange(val: number) {
  searchCondition.current = 1;
  searchCondition.size = val;
  getTableInfo();
}

/* 触发处理 查看编辑事件 */
function handleViewEdit(row: INumberCardOrderInfoList, code: ViewModeFilter) {
  emit("handleViewEdit", row.id, code);
}

/* 双击当前行 */
function rowDblclick(row: INumberCardOrderInfoList) {
  multipleTableRef.value!.toggleRowSelection(row);
}

/* 取消订单 */
function handleCancelOrder(id: number) {
  toggleState(true);
  putCancelCardContractPackageOrderInfo({ id })
    .then(res => {
      ElMessage.success(res.msg);
      /* 修改订单状态 */
      handleChangeOrderStatus(id, "canceled");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 修改订单状态 */
function handleChangeOrderStatus(id: number, status: string) {
  const item = tableList.value.find(item => item.id === id);
  if (item) {
    item.status = status;
    item.status_name = orderStatus.find(s => s.dictValue === status)?.dictLabel || "";
  }
}
getTableInfo();
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.mb10 {
  margin-bottom: 10px;
}
/* 关键：列表右侧操作按钮的对其 */
:deep(.el-space__item) {
  line-height: 15px;
}

.el-button.is-text + .el-button.is-text {
  margin-left: 0;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}
.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

.w-tag .el-tag {
  margin: 2px 5px;
}
</style>
